package com.example.composedemo

import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.viewinterop.AndroidView

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
                WebViewPage(modifier = Modifier.fillMaxSize(), linkUrl = "https://juejin.cn/android")
            }
        }
    }
}

@Composable
fun WebViewPage(modifier: Modifier = Modifier, linkUrl: String) {
    Column(modifier = modifier.fillMaxSize()) {
        AndroidView(modifier = modifier.fillMaxSize(),
            factory = {
                val webView = WebView(it)
                webView.settings.javaScriptEnabled = true
                webView.settings.javaScriptCanOpenWindowsAutomatically = true
                webView.settings.domStorageEnabled = true
                webView.settings.loadsImagesAutomatically = true
                webView.settings.mediaPlaybackRequiresUserGesture = false
                webView.webViewClient = WebViewClient()
                webView.loadUrl(linkUrl)
                webView
            })
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    WebViewPage(linkUrl = "https://juejin.cn/android")
}